import React, { useCallback } from 'react';
import { Button } from 'antd';
import { difference } from 'lodash';
import type { Direction } from './index';
import { getRowKey } from './utils';
import styles from './index.less';

interface OperateProps {
  leftSelectedRows: any[];
  rightSelectedRows: any[];
  targetKeys: string[];
  rowKey: any;
  disabled: boolean;
  onChange: (targetKeys: string[], direction: Direction, moveKeys: string[]) => void;
}

/**
 * 中间的操作按钮
 */
export default (props: OperateProps) => {
  const { leftSelectedRows, rightSelectedRows, targetKeys, rowKey, disabled, onChange: outOnChange } = props;

  const onChange = useCallback(
    (direction: Direction) => {
      let newTargetKeys: string[] = [...targetKeys];
      let moveKeys = [];
      if (direction === 'right') {
        moveKeys = leftSelectedRows.map((item) => getRowKey(item, rowKey));
        newTargetKeys = newTargetKeys.concat(moveKeys);
      } else {
        moveKeys = rightSelectedRows.map((item) => getRowKey(item, rowKey));
        newTargetKeys = difference(targetKeys, moveKeys);
      }

      outOnChange && outOnChange(newTargetKeys, direction, moveKeys);
    },
    [leftSelectedRows, rightSelectedRows, targetKeys, rowKey, outOnChange],
  );

  return (
    <div className={styles.operate}>
      <Button
        type="primary"
        icon="right"
        size="small"
        disabled={leftSelectedRows.length === 0 || disabled}
        onClick={onChange.bind(null, 'right')}
      />
      <Button
        type="primary"
        icon="left"
        size="small"
        disabled={rightSelectedRows.length === 0 || disabled}
        onClick={onChange.bind(null, 'left')}
      />
    </div>
  );
};
